package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);

    }

    @Override
    public void save(Employee employee, Long[] ids) {
        employeeMapper.insert(employee);

        if (ids != null && ids.length>0 ){
            for (Long roleId : ids) {
                employeeMapper.insertIN(employee.getId(), roleId);
            }
        }

    }

    @Override
    public Employee get(Long id) {

        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);

        //删除关系
        employeeMapper.deleteRelation(employee.getId());

        if (ids != null && ids.length>0 ){
            for (Long roleId : ids) {
                employeeMapper.insertIN(employee.getId(), roleId);
            }
        }

    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {

        /*int totalCount = employeeMapper.queryForCount(qo);

        if (totalCount == 0){
            return  new PageResult<>(qo.getCurrentPage(), qo.getPageSize(),
                    totalCount, Collections.EMPTY_LIST);
        }
        //获取总页数
        int totalPage = totalCount % qo.getPageSize()== 0 ?
                totalCount / qo.getPageSize() : totalCount / qo.getPageSize() +1;
        //判断当前页是否大于总页数
        if (qo.getCurrentPage() > totalPage){
            qo.setCurrentPage(totalPage);
        }*/

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.queryForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {

        if (! StringUtils.hasText(username)){
            throw new LogicException("用户名不能为空");
        }
        if (! StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if (employee != null && ! employee.isStatus()){
            throw new LogicException("账号已被禁用,请联系管理员");
        }
        if (employee == null){
            throw new LogicException("用户名或密码错误");
        }
        return employee;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        //判空
        if (!StringUtils.hasText(oldPassword)){
            throw new LogicException("原密码不能为空");
        }
        if (! StringUtils.hasText(newPassword)){
            throw new LogicException("新密码不能为空");
        }

        String password = UserContext.getCurrentUser().getPassword();
        System.out.println(password);
        if ( ! oldPassword.equals(password)){
            throw new LogicException("原密码错误");
        }
        //修改密码
        employeeMapper.updatePassword(UserContext.getCurrentUser().getId(),newPassword);
    }

    @Override
    public void resetPwd(Long id, String newPassword) {
        if (id == null) {
            throw new LogicException("操作错误");
        }
        if ( ! StringUtils.hasText(newPassword)) {
            throw new LogicException("新密码不能为空");
        }

        employeeMapper.updatePassword(id, newPassword);
    }

    @Override
    public void renew(Long id) {
        if (id == null) {
            throw new LogicException("操作错误");
        }
        boolean result = employeeMapper.selectStatus(id);
        employeeMapper.updateStatus(id,! result);
    }

    @Override
    public void batchDelete(Long[] ids) {
        if (ids != null && ids.length > 0) {
            employeeMapper.batchDelete(ids);
        }
    }

    @Override
    public boolean selectByName(Long id,String name) {
        if (id != null && StringUtils.hasText(name)){
            if (employeeMapper.selectByPrimaryKey(id).getName().equals(name)){
                return true;

            }
        }
       /* List<Employee> employees = employeeMapper.selectAll();
        for (Employee employee : employees) {
            if (id!= null && employee.getId()==id){
                if (employee.getName().equals(name)){
                    return true;
                }
            }else {
                if (employee.getName().equals(name)){
                    return false;
                }
            }
        }*/

        if (StringUtils.hasText(name)){
            if (employeeMapper.selectByName(name) == null) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Workbook exportXls() {
        //查询所有员工
        List<Employee> employees = employeeMapper.selectAll();
        //使用poi创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet
        Sheet sheet = wb.createSheet("员工通讯录");
        //创建标题行数据
        Row row = sheet.createRow(0);
        //创建内容到标题行,从0开始
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //设置内容到单元格中
        for (int i = 0; i < employees.size(); i++) {
            //获取员工数据
            Employee employee = employees.get(i);
            //每个员工创建一行数据
            row = sheet.createRow(i+1);
            //创建内容到行,从0开始
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取上传的文件, 并且封装为一个Workbook 对象
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //标题行0不用读, lastRowNum 是代表索引, 需要使用<=
        for (int i = 1; i <= lastRowNum ; i++) {
            Row row = sheet.getRow(i);
            //创建对象封装数据
            Employee employee = new Employee();
            //任何数据有空值都会跳过
            if (row == null|| row.getCell(0) == null ||row.getCell(0).equals("")
                    || row.getCell(1) == null || row.getCell(1).equals("")
                    || row.getCell(2) == null || row.getCell(2).equals("")){
                continue;
            }
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            Cell cell = row.getCell(2);
            //判断数据传入的类型
            if (cell.getCellType() == CellType.NUMERIC){
                employee.setAge((int)cell.getNumericCellValue());
            }else {
                employee.setAge(Integer.valueOf(cell.getStringCellValue()));
            }
            //将数据插入到数据库
            employeeMapper.insert(employee);
        }
    }


}
